package com.jfinal.weixin.util;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

public class HttpUtil {
	/**
	 * 创建SSLClient
	 * @return
	 */
	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
					null, new TrustStrategy() {
						public boolean isTrusted(X509Certificate[] chain,
								String authType) throws CertificateException {
							return true;
						}
					}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}
	
	public interface MachineCallback {
		void callMessage(String message);
		void callError();
	}
	
	public static void post(String url,Map<String,String> header,List<NameValuePair> nvps,MachineCallback callback){
		//创建httpClient
		CloseableHttpClient httpClient = HttpUtil
				.createSSLClientDefault();
		try {
			
			//设置 httpClient请求方式为HttpPost
			HttpPost httpPost = new HttpPost(url);
			
			if (header != null && !header.isEmpty()) {
				Iterator<Map.Entry<String, String>> entries = header.entrySet().iterator();  
				while (entries.hasNext()) {
				    Map.Entry<String, String> entry = entries.next();
				    httpPost.setHeader(entry.getKey(), entry.getValue());
				}
			}
			if (nvps != null) {
				httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			}
			//发送并返回发送结果
			HttpResponse response = httpClient.execute(httpPost);
			String result = "";
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "UTF-8");
				}
			}
			
			//关闭连接
			httpClient.close();
			
//			System.out.println(result);
			if (callback != null) {
				callback.callMessage(result);
			}
			
		} catch (Exception e) {
			if (httpClient!=null) {
				try {
					httpClient.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			if (callback != null) {
				callback.callError();
			}
		}
	}
	
	public static void get(String url,Map<String,String> header,MachineCallback callback) {
		//创建httpClient
		CloseableHttpClient httpClient = HttpUtil
				.createSSLClientDefault();
		String result = "";
		try {
			
			//设置 httpClient请求方式为HttpPost
			HttpGet httpGet = new HttpGet(url);
			
			if (header != null && !header.isEmpty()) {
				Iterator<Map.Entry<String, String>> entries = header.entrySet().iterator();  
				while (entries.hasNext()) {
				    Map.Entry<String, String> entry = entries.next();
				    httpGet.setHeader(entry.getKey(), entry.getValue());
				}
			}
			
			//发送并返回发送结果
			HttpResponse response = httpClient.execute(httpGet);
			
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "UTF-8");
				}
			}
			//关闭连接
			httpClient.close();
			
//			System.out.println(result);
			if (callback != null) {
				callback.callMessage(result);
			}
			
		} catch (Exception e) {
			if (httpClient!=null) {
				try {
					httpClient.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			if (callback != null) {
				callback.callMessage(result+e.getMessage());
			}
		}
	}
	
}
